import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Spin, Button, Tag, Breadcrumb } from 'antd';
import { useMessage } from '../../hooks/useMessage';
import { useError } from '../../components/ui/ErrorHandler';
import { useLoading } from '../../components/ui/LoadingManager';
import Loading from '../../components/ui/Loading';
import { 
  ArrowLeftOutlined, 
  PhoneOutlined, 
  MessageOutlined, 
  HeartOutlined,
  ShareAltOutlined,
  HomeOutlined,
  AppstoreOutlined,
  CheckCircleOutlined,
  StarFilled,
  CustomerServiceOutlined,
  DesktopOutlined,
  FileTextOutlined,
  ToolOutlined,
  SafetyCertificateOutlined,
  TagOutlined,
  StarOutlined
} from '@ant-design/icons';
import { productApi } from '../../services/api';
import ContactModal from '../../components/ui/ContactModal';
import { Product } from '../../types';



const ProductDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const message = useMessage();
  const { showError } = useError();
  const { withLoading } = useLoading();
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [contactModalOpen, setContactModalOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);
  const [selectedCraftType, setSelectedCraftType] = useState<string | null>(null);
  const [selectedCraftData, setSelectedCraftData] = useState<any>(null);

  // 模拟产品数据
  const mockProduct: Product = {
    id: '1',
    name: '发光字',
    description: '高品质LED发光字，适用于各种商业场所的标识展示，具有节能环保、亮度高、寿命长等特点。',
    type: '标识导视',
    categoryId: 'cat_1',
    images: [
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=LED%20illuminated%20signage%20letters%20modern%20design%20professional%20display&image_size=square',
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=acrylic%20LED%20letters%20night%20illumination%20commercial%20signage&image_size=square',
      'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=metal%20channel%20letters%20LED%20backlit%20storefront%20sign&image_size=square'
    ],
    features: ['节能环保', '高亮度', '长寿命', '防水防尘', '定制化'],
    tags: ['LED', '发光字', '标识', '商业'],
    specifications: {
      material: 'LED灯珠',
      brightness: '3000流明',
      lifespan: '50000小时',
      protection: 'IP65'
    },
    craftTypes: ['无边发光字', '树脂字', '铁皮字'],
    status: 'active',
    featured: true,
    sort: 1,
    createdAt: '2024-01-01',
    updatedAt: '2024-01-01'
  };

  useEffect(() => {
    const fetchProduct = async () => {
      if (!id) {
        showError('产品ID不存在');
        navigate('/products');
        return;
      }
      
      try {
        const product = await withLoading(
          productApi.getProduct(id),
          '正在加载产品详情...'
        );
        setProduct(product);
        
        // 设置默认选择的工艺类型和数据
        if (product.craftTypes && product.craftTypes.length > 0) {
          let craftTypes = product.craftTypes;
          // 如果craftTypes是字符串，尝试解析为JSON
          if (typeof craftTypes === 'string') {
            try {
              craftTypes = JSON.parse(craftTypes);
            } catch (e) {
              console.warn('Failed to parse craftTypes:', e);
              craftTypes = product.craftTypes;
            }
          }
          
          const firstCraftType = Array.isArray(craftTypes) ? craftTypes[0] : craftTypes;
          const craftName = typeof firstCraftType === 'string' ? firstCraftType : (firstCraftType as any)?.name || '未知工艺';
          setSelectedCraftType(craftName);
          setSelectedCraftData(typeof firstCraftType === 'object' ? firstCraftType : null);
        }
      } catch (error) {
        console.error('获取产品详情失败:', error);
        showError(error instanceof Error ? error : '获取产品详情失败', {
          modal: true,
          details: '请检查网络连接或稍后重试'
        });
        // 如果API失败，使用模拟数据作为后备
        setProduct(mockProduct);
        if (mockProduct.craftTypes && mockProduct.craftTypes.length > 0) {
          let craftTypes = mockProduct.craftTypes;
          // 如果craftTypes是字符串，尝试解析为JSON
          if (typeof craftTypes === 'string') {
            try {
              craftTypes = JSON.parse(craftTypes);
            } catch (e) {
              console.warn('Failed to parse craftTypes:', e);
              craftTypes = mockProduct.craftTypes;
            }
          }
          
          const firstCraftType = Array.isArray(craftTypes) ? craftTypes[0] : craftTypes;
          const craftName = typeof firstCraftType === 'string' ? firstCraftType : (firstCraftType as any)?.name || '未知工艺';
          setSelectedCraftType(craftName);
          setSelectedCraftData(typeof firstCraftType === 'object' ? firstCraftType : null);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchProduct();
  }, [id]); // 只依赖id，其他函数已经用useCallback包装



  if (loading) {
    return (
      <Loading 
        text="正在加载产品详情..." 
        overlay={true}
        size="large"
      />
    );
  }

  if (!product) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-600 mb-4">产品不存在</h2>
          <Button onClick={() => navigate('/products')} type="primary">
            返回产品列表
          </Button>
        </div>
      </div>
    );
  }

  // 根据选中的工艺类型获取对应的图片
  const getCurrentImages = () => {
    if (selectedCraftData && selectedCraftData.image) {
      return [selectedCraftData.image];
    }
    
    // 如果产品images是字符串，尝试解析
    let productImages = product?.images || [];
    if (typeof productImages === 'string') {
      try {
        productImages = JSON.parse(productImages);
      } catch (e) {
        console.warn('Failed to parse product images:', e);
        productImages = [];
      }
    }
    
    return Array.isArray(productImages) ? productImages : [];
  };
  
  const currentImages = getCurrentImages();

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 顶部导航 */}
      <div className="bg-white shadow-sm sticky top-0 z-10">
        <div className="container mx-auto px-3 sm:px-4 py-3 sm:py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 sm:gap-4 flex-1">
              <Button 
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate('/products')}
                type="text"
                shape="circle"
                size={window.innerWidth < 640 ? 'middle' : 'large'}
                className="text-blue-600 hover:text-blue-700 hover:bg-blue-50 flex-shrink-0"
              />
              <Breadcrumb
                className="flex-1 min-w-0"
                items={[
                  {
                    title: (
                      <div className="flex items-center gap-1 text-gray-600">
                        <HomeOutlined className="text-xs sm:text-sm" />
                        <span className="text-xs sm:text-sm hidden sm:inline">首页</span>
                      </div>
                    ),
                    onClick: () => navigate('/')
                  },
                  {
                    title: (
                      <div className="flex items-center gap-1 text-gray-600">
                        <AppstoreOutlined className="text-xs sm:text-sm" />
                        <span className="text-xs sm:text-sm">产品</span>
                      </div>
                    ),
                    onClick: () => navigate('/products')
                  },
                  {
                    title: <span className="text-xs sm:text-sm truncate max-w-[100px] sm:max-w-none">{product.name}</span>
                  }
                ]}
              />
            </div>
            <div className="flex items-center gap-1 sm:gap-2 flex-shrink-0">
              <Button 
                icon={<ShareAltOutlined />} 
                type="text"
                size={window.innerWidth < 640 ? 'small' : 'middle'}
                onClick={() => {
                  navigator.clipboard.writeText(window.location.href);
                  message.success('链接已复制到剪贴板');
                }}
                className="text-xs sm:text-sm"
              >
                <span className="hidden sm:inline">分享</span>
              </Button>
            </div>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-3 sm:px-4 py-4 sm:py-6 md:py-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6 md:gap-8 lg:gap-12">
          {/* 左侧工艺详情图 */}
          <div className="space-y-3 sm:space-y-4">
            {/* 主图 */}
            <div className="aspect-square bg-white rounded-lg overflow-hidden shadow-lg border border-gray-200">
              <img
                src={currentImages[selectedImageIndex] || 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=modern%20advertising%20signage%20product%20professional%20display&image_size=square'}
                alt={selectedCraftType ? `${product.name} - ${selectedCraftType}` : product.name}
                className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
              />
            </div>
            
            {/* 缩略图 */}
            {currentImages.length > 1 && (
              <div className="flex gap-2 overflow-x-auto pb-2">
                {currentImages.map((image, index) => (
                  <div
                    key={index}
                    className={`flex-shrink-0 w-16 h-16 sm:w-20 sm:h-20 rounded-lg overflow-hidden cursor-pointer border-2 transition-all duration-300 ${
                      selectedImageIndex === index ? 'border-blue-500 shadow-lg' : 'border-gray-200 hover:border-blue-300'
                    }`}
                    onClick={() => setSelectedImageIndex(index)}
                  >
                    <img
                      src={image}
                      alt={`${product.name} ${index + 1}`}
                      className="w-full h-full object-cover"
                    />
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 右侧产品信息 */}
          <div className="space-y-4 sm:space-y-6">
            {/* 基本信息 */}
            <div className="bg-white rounded-xl p-4 sm:p-6 md:p-8 shadow-lg border border-gray-100 relative overflow-hidden">
              {/* 背景装饰 */}
              <div className="absolute top-0 right-0 w-24 h-24 sm:w-32 sm:h-32 bg-gradient-to-bl from-blue-50 to-transparent rounded-bl-full opacity-50"></div>
              
              <h1 className="text-xl sm:text-2xl lg:text-3xl xl:text-4xl font-bold bg-gradient-to-r from-gray-900 to-blue-800 bg-clip-text text-transparent mb-4 sm:mb-6 leading-tight">
                {selectedCraftType ? `${product.name} - ${selectedCraftType}` : product.name}
              </h1>
              
              <p className="text-gray-700 mb-6 sm:mb-8 leading-relaxed text-sm sm:text-base lg:text-lg">
                {product.description}
              </p>
              
              {/* 产品信息 */}
              <div className="space-y-3 sm:space-y-4 mb-6 sm:mb-8">
                <div className="grid grid-cols-1 gap-2 sm:gap-3">
                  <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-blue-50 rounded-lg border border-blue-200">
                    <TagOutlined className="text-blue-600 text-sm sm:text-lg flex-shrink-0" />
                    <div className="flex items-center gap-1 sm:gap-2 min-w-0">
                      <span className="text-xs sm:text-sm text-blue-600 font-medium">产品分类:</span>
                      <span className="font-semibold text-blue-800 text-xs sm:text-sm truncate">{product.type}</span>
                    </div>
                  </div>

                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
                  {product.features?.slice(0, 4).map((feature, index) => (
                    <div key={index} className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-gray-50 rounded-lg">
                      <StarOutlined className="text-orange-500 text-sm sm:text-lg flex-shrink-0" />
                      <div className="font-semibold text-gray-900 text-xs sm:text-sm truncate">{feature}</div>
                    </div>
                  ))}
                </div>
              </div>
              
              {/* 价格显示区域 - 重新设计 */}
              <div className="mt-4 sm:mt-6 p-4 sm:p-6 bg-gradient-to-r from-red-50 to-orange-50 rounded-xl border-2 border-red-100">
                <div className="flex items-center justify-between gap-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-baseline gap-1 sm:gap-2 mb-2">
                      <span className="text-2xl sm:text-3xl lg:text-4xl font-bold text-red-600">询价</span>
                      <span className="text-sm sm:text-lg lg:text-xl font-medium text-red-500">/平方米</span>
                    </div>
                    <p className="text-xs sm:text-sm text-gray-600 leading-relaxed">
                      具体价格根据工艺材料而定，请联系客服获取精准报价
                    </p>
                  </div>
                  <div className="ml-3 sm:ml-6 flex-shrink-0">
                    <div className="w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full flex items-center justify-center">
                      <PhoneOutlined className="text-lg sm:text-2xl text-red-600" />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 工艺类型选择器 */}
            <div className="bg-white rounded-lg p-3 sm:p-4 md:p-6 shadow-sm border border-gray-200">
              <h3 className="text-base sm:text-lg font-bold text-gray-900 mb-3 sm:mb-4">选择产品工艺类型</h3>
              <div className="grid grid-cols-1 gap-2 sm:gap-3">
                {(() => {
                  // 解析craftTypes数据
                  let craftTypes = product.craftTypes || [];
                  if (typeof craftTypes === 'string') {
                    try {
                      craftTypes = JSON.parse(craftTypes);
                    } catch (e) {
                      console.warn('Failed to parse craftTypes:', e);
                      craftTypes = [];
                    }
                  }
                  
                  return Array.isArray(craftTypes) ? craftTypes.map((craftType, index) => {
                    // 处理craftType可能是字符串或对象的情况
                    const craftName = typeof craftType === 'string' ? craftType : (craftType as any)?.name || '未知工艺';
                    const craftDescription = typeof craftType === 'object' && (craftType as any)?.description ? (craftType as any).description : '专业工艺制作，品质保证';
                    
                    return (
                      <div
                        key={index}
                        className={`border-2 rounded-lg p-3 sm:p-4 cursor-pointer transition-all duration-300 ${
                          selectedCraftType === craftName
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-blue-300 hover:bg-gray-50'
                        }`}
                        onClick={() => {
                          setSelectedCraftType(craftName);
                          setSelectedCraftData(typeof craftType === 'object' ? craftType : null);
                          setSelectedImageIndex(0); // 重置图片索引
                        }}
                      >
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2">
                            <h4 className="font-semibold text-gray-900 text-sm sm:text-base truncate">{craftName}</h4>
                          </div>
                          <p className="text-xs sm:text-sm text-gray-600 mb-1 sm:mb-2 line-clamp-2">{craftDescription}</p>
                        </div>
                        {selectedCraftType === craftName && (
                          <CheckCircleOutlined className="text-blue-500 text-base sm:text-lg ml-2 sm:ml-3 flex-shrink-0" />
                        )}
                      </div>
                    </div>
                    );
                  }) : [];
                })()}
              </div>
            </div>

            {/* 立刻咨询报价按钮 */}
            <div className="bg-white rounded-lg p-4 sm:p-6 shadow-sm border border-gray-200">
              <Button
                type="primary"
                size={window.innerWidth < 640 ? 'middle' : 'large'}
                icon={<PhoneOutlined />}
                className="w-full h-10 sm:h-12 text-sm sm:text-lg font-semibold bg-blue-600 hover:bg-blue-700"
                onClick={() => setContactModalOpen(true)}
              >
                立刻咨询报价
              </Button>
              
              <div className="mt-3 sm:mt-4 text-center">
                <p className="text-xs sm:text-sm text-gray-500">
                  💡 专业客服为您提供定制化方案和精准报价
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* 详细信息区域 */}
        <div className="mt-6 sm:mt-8 md:mt-12 space-y-4 sm:space-y-6 md:space-y-8">
          {/* 技术规格 */}
          {selectedCraftType && (
            <div className="bg-white rounded-lg p-4 sm:p-6 lg:p-8 shadow-sm border border-gray-200">
              <h2 className="text-lg sm:text-xl lg:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">技术规格 - {selectedCraftType}</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4 md:gap-6">
                {selectedCraftData && selectedCraftData.specifications ? (
                  Object.entries(selectedCraftData.specifications).map(([key, value], index) => (
                    <div key={index} className="bg-gray-50 rounded-lg p-3 sm:p-4">
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2">
                        <span className="text-gray-600 font-medium text-xs sm:text-sm">{key}：</span>
                        <span className="text-gray-900 font-semibold text-xs sm:text-sm truncate">{value as string}</span>
                      </div>
                    </div>
                  ))
                ) : (
                  // 默认规格显示
                  <>
                    <div className="bg-gray-50 rounded-lg p-3 sm:p-4">
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2">
                        <span className="text-gray-600 font-medium text-xs sm:text-sm">工艺类型：</span>
                        <span className="text-gray-900 font-semibold text-xs sm:text-sm truncate">{selectedCraftType}</span>
                      </div>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3 sm:p-4">
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2">
                        <span className="text-gray-600 font-medium text-xs sm:text-sm">材质：</span>
                        <span className="text-gray-900 font-semibold text-xs sm:text-sm truncate">优质材料</span>
                      </div>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3 sm:p-4">
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1 sm:gap-2">
                        <span className="text-gray-600 font-medium text-xs sm:text-sm">质保期：</span>
                        <span className="text-gray-900 font-semibold text-xs sm:text-sm truncate">3年</span>
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}

          {/* 服务流程 */}
          <div className="bg-white rounded-lg p-4 sm:p-6 lg:p-8 shadow-sm border border-gray-200">
            <h2 className="text-lg sm:text-xl lg:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">服务流程</h2>
            <div className="flex flex-col md:flex-row items-center justify-between gap-4 sm:gap-6 md:gap-8">
              {[
                { step: '01', title: '需求咨询', desc: '了解客户具体需求和使用场景', icon: <CustomerServiceOutlined /> },
                { step: '02', title: '方案设计', desc: '制定专业的设计方案和报价', icon: <DesktopOutlined /> },
                { step: '03', title: '合同签订', desc: '确认方案后签订正式合同', icon: <FileTextOutlined /> },
                { step: '04', title: '生产制作', desc: '按照标准流程进行生产制作', icon: <ToolOutlined /> },
                { step: '05', title: '安装验收', desc: '专业团队安装并进行验收', icon: <SafetyCertificateOutlined /> }
              ].map((item, index) => (
                <React.Fragment key={index}>
                  <div className="text-center flex-1">
                    <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4 shadow-lg">
                      <span className="text-lg sm:text-xl lg:text-2xl">{item.icon}</span>
                    </div>
                    <div className="bg-blue-50 rounded-lg p-3 sm:p-4 border border-blue-100">
                      <h3 className="font-bold text-gray-900 mb-1 sm:mb-2 text-sm sm:text-base lg:text-lg">{item.title}</h3>
                      <p className="text-xs sm:text-sm text-gray-600 leading-relaxed">{item.desc}</p>
                    </div>
                  </div>
                  {index < 4 && (
                    <div className="hidden md:flex items-center justify-center">
                      <div className="text-blue-400 text-xl lg:text-2xl">→</div>
                    </div>
                  )}
                </React.Fragment>
              ))}
            </div>
          </div>

          {/* 售后服务 */}
          <div className="bg-white rounded-lg p-4 sm:p-6 lg:p-8 shadow-sm border border-gray-200">
            <h2 className="text-lg sm:text-xl lg:text-2xl font-bold text-gray-900 mb-4 sm:mb-6">售后服务</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
              <div className="text-center">
                <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <CheckCircleOutlined className="text-lg sm:text-xl lg:text-2xl text-blue-600" />
                </div>
                <h3 className="font-semibold text-gray-900 mb-1 sm:mb-2 text-sm sm:text-base">质量保证</h3>
                <p className="text-xs sm:text-sm text-gray-600">产品质量保证3年，非人为损坏免费维修</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <PhoneOutlined className="text-lg sm:text-xl lg:text-2xl text-green-600" />
                </div>
                <h3 className="font-semibold text-gray-900 mb-1 sm:mb-2 text-sm sm:text-base">24小时服务</h3>
                <p className="text-xs sm:text-sm text-gray-600">7×24小时客服热线，随时为您解答疑问</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-orange-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <MessageOutlined className="text-lg sm:text-xl lg:text-2xl text-orange-600" />
                </div>
                <h3 className="font-semibold text-gray-900 mb-1 sm:mb-2 text-sm sm:text-base">技术支持</h3>
                <p className="text-xs sm:text-sm text-gray-600">专业技术团队提供安装指导和技术支持</p>
              </div>
              <div className="text-center">
                <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <StarFilled className="text-lg sm:text-xl lg:text-2xl text-purple-600" />
                </div>
                <h3 className="font-semibold text-gray-900 mb-1 sm:mb-2 text-sm sm:text-base">定制服务</h3>
                <p className="text-xs sm:text-sm text-gray-600">根据客户需求提供个性化定制方案</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 联系弹窗 */}
      <ContactModal
        open={contactModalOpen}
        onClose={() => setContactModalOpen(false)}
      />
    </div>
  );
};

export default ProductDetailPage;